package com.jinyang.jetpackdemo.activity

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.arch.core.util.Function
import androidx.core.app.ActivityCompat
import androidx.lifecycle.*
import com.jinyang.jetpackdemo.R
import com.jinyang.jetpackdemo.util.LjyLogUtil
import com.jinyang.jetpackdemo.util.LocationUtil
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LiveDataActivity : AppCompatActivity() {
    private lateinit var mMutableLiveData: MutableLiveData<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_live_data)

        //1.创建LiveData实例，指定源数据类型
        mMutableLiveData = MutableLiveData<String>()

        //2. 创建Observer实例，实现onChanged()方法，用于接收源数据变化并刷新UI
        val observer = Observer<String> {
            LjyLogUtil.d("mMutableLiveData.observe.onChanged:${it}")
        }

        //3 LiveData实例使用observe()方法添加观察者observer，并传入LifecycleOwner
        mMutableLiveData.observe(this, observer)
        //4 更改LiveData中的数据
        //4.1 如果想要在LiveData对象分发给观察者之前对其中存储的值进行更改，可以使用Transformations.map()
        val mapLiveData = Transformations.map(mMutableLiveData, Function {
            it + "_LJY"
        })
        mapLiveData.observe(this, Observer {
            LjyLogUtil.d("mapLiveData.observe.onChanged:${it}")
        })
        //4.2 Transformations.switchMap(),切换监听
        val liveData0 = MutableLiveData<Boolean>()
        val liveData1 = MutableLiveData<String>()
        val liveData2 = MutableLiveData<String>()
        val switchMapLiveData = Transformations.switchMap(liveData0, Function {
            if (it) {
                liveData1
            } else {
                liveData2
            }
        })
        switchMapLiveData.observe(this, Observer {
            LjyLogUtil.d("switchMapLiveData.observe.onChanged:${it}")
        })
        liveData1.value = "123"
        liveData2.value = "456"
        liveData0.value = false
        //5. 合并多个LiveData数据源
        //MediatorLiveData继承自mutableLiveData，它将多个LiveData数据源集合起来，一个组件监听多个LiveData数据变化的目的
        val mediatorLiveData = MediatorLiveData<String>()
        mediatorLiveData.addSource(liveData0, Observer {
            LjyLogUtil.d("mediatorLiveData.addSource(liveData0):$it")
        })
        mediatorLiveData.addSource(liveData1, Observer {
            LjyLogUtil.d("mediatorLiveData.addSource(liveData1):$it")
        })
        mediatorLiveData.addSource(liveData2, Observer {
            LjyLogUtil.d("mediatorLiveData.addSource(liveData2):$it")
        })
        mediatorLiveData.observe(this, Observer {
            LjyLogUtil.d("mediatorLiveData.observe:$it")

        })
        liveData1.value = "321"
        liveData2.value = "654"
        //6. LiveData实例使用setValue()/postValue()更新源数据 （子线程要postValue()）
        LjyLogUtil.d("onCreate")
        mMutableLiveData.value = "value=onCreate"
        GlobalScope.launch {
            liveData0.postValue(true)
            delay(2000)
            mMutableLiveData.postValue("value=GlobalScope")
            liveData0.postValue(false)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                    arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    ), 10001
                )
            } else {
                MyLiveData.get(this)?.observe(this, Observer {
                    LjyLogUtil.d("LiveDataActivity:$it")
                })
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode==10001){
            MyLiveData.get(this)?.observe(this, Observer {
                LjyLogUtil.d("LiveDataActivity:$it")
            })
        }
    }

    override fun onStart() {
        super.onStart()
        LjyLogUtil.d("onStart")
        mMutableLiveData.value = "value=onStart"
    }

    override fun onResume() {
        super.onResume()
        LjyLogUtil.d("onResume")
        mMutableLiveData.value = "value=onResume"
    }

    override fun onPause() {
        super.onPause()
        LjyLogUtil.d("onPause")
        mMutableLiveData.value = "value=onPause"
    }

    override fun onStop() {
        super.onStop()
        LjyLogUtil.d("onStop")
        mMutableLiveData.value = "value=onStop"
    }

    override fun onDestroy() {
        super.onDestroy()
        LjyLogUtil.d("onDestroy")
        mMutableLiveData.value = "value=onDestroy"
    }
}

class MyLiveData(context: Context) : LiveData<String>() {
    init {
        LocationUtil.getInstance().getLocation(context)
    }

    companion object {
        var instance: MyLiveData? = null
        fun get(context: Context): MyLiveData? {
            if (instance == null) {
                instance = MyLiveData(context)
            }
            return instance
        }
    }

    val callback = LocationUtil.CallBack() {
        value = it
    }

    override fun onActive() {
        super.onActive()
        LjyLogUtil.d("MyLiveData.onActive")
        LocationUtil.getInstance().setCallBack(callback)
    }

    override fun onInactive() {
        super.onInactive()
        LjyLogUtil.d("MyLiveData.onInactive")
        LocationUtil.getInstance().removeCallBack()
    }
}

